package com.piggy.logi.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.enums.CacheKeyEnums;
import com.piggy.common.core.exception.CustomException;
import com.piggy.common.core.exception.GlobalException;
import com.piggy.common.core.exception.base.BaseException;
import com.piggy.common.core.utils.FeignResultUtils;
import com.piggy.common.core.utils.PageUtils;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.common.core.web.service.BaseService;
import com.piggy.common.redis.cache.CacheUtils;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.logi.common.datascope.annotation.LogiDataScope;
import com.piggy.logi.sys.api.bo.LogiSysDeptExtCusEditBo;
import com.piggy.logi.sys.api.domain.*;
import com.piggy.logi.sys.api.vo.LogiSysDeptExtVo;
import com.piggy.logi.sys.domain.LogiAccountLog;
import com.piggy.logi.sys.domain.LogiSysUserPost;
import com.piggy.logi.sys.mapper.*;
import com.piggy.logi.sys.service.*;
import com.piggy.sys.api.RemoteDistrictService;
import com.piggy.sys.api.RemoteSmsService;
import com.piggy.sys.api.vo.BaseAddressVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author shark
 */
@Slf4j
@Service
public class LogiSysUserServiceImpl extends ServiceImpl<LogiSysUserMapper, LogiSysUser> implements ILogiSysUserService, BaseService {

    @Resource
    private LogiSysRoleMapper roleMapper;

    @Resource
    private LogiSysPostMapper postMapper;

    @Resource
    private LogiSysUserRoleMapper userRoleMapper;

    @Resource
    private LogiSysUserPostMapper userPostMapper;

    @Resource
    private ILogiSysPermissionService permissionService;

    @Resource
    private ILogiSysDeptExtService extService;

    @Resource
    private ILogiSysDeptService deptService;

    @Resource
    private RemoteDistrictService districtService;

    @Resource
    private RemoteSmsService smsService;

    @Resource
    private ILogiSysPostService postService;

    @Resource
    private ILogiSysRoleService roleService;

    @Resource
    private ILogiAccountLogService logiAccountLogService;

    @Override
    @LogiDataScope(deptAlias = "d", userAlias = "u")
    public TableDataInfo<LogiSysUser> selectPageUserList(LogiSysUser user) {
        PageInfo<LogiSysUser> result = PageHelper.startPage(user).doSelectPageInfo(() -> getUsersFillDept(baseMapper.selectUserList(user)));
        return PageUtils.buildDataInfo(result);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @LogiDataScope(deptAlias = "d", userAlias = "u")
    public List<LogiSysUser> selectUserList(LogiSysUser user) {
        return getUsersFillDept(baseMapper.selectUserList(user));
    }

    @Override
    public List<LogiSysUser> selectUserDeptExtList(LogiSysUser user) {
        if (ObjectUtil.isAllNotEmpty(user.getDept().getCreateTimeBegin(), user.getDept().getCreateTimeEnd())) {
            Calendar calendarEnd = Calendar.getInstance();
            calendarEnd.setTime(user.getDept().getCreateTimeEnd());
            calendarEnd.set(Calendar.HOUR_OF_DAY, 23);
            calendarEnd.set(Calendar.MINUTE, 59);
            calendarEnd.set(Calendar.SECOND, 59);
            //防止mysql自动加一秒,毫秒设为0
            calendarEnd.set(Calendar.MILLISECOND, 0);

            user.getDept().setCreateTimeEnd(calendarEnd.getTime());
        }
        return getUsersFillDept(baseMapper.selectUserList(user));
    }

    private List<LogiSysUser> getUsersFillDept(List<LogiSysUser> users) {
        users.stream().peek(this::fillDept).collect(Collectors.toList());
        return users;
    }

    private LogiSysUser fillDept(LogiSysUser user) {
        if (ObjectUtil.isEmpty(user)) {
            return user;
        }
        if (ObjectUtil.isNotEmpty(user.getDept().getDeptDistrict())) {
            R<BaseAddressVo> voR = districtService.getDistrictVo(ObjectUtil.defaultIfNull(user.getDept().getDeptDistrict(), 0L).toString(), SecurityConstants.INNER);
            FeignResultUtils.throwIfFailed(voR);
            BaseAddressVo vo = voR.getData();
            if (ObjectUtil.isNotEmpty(vo)) {
                user.getDept().setDeptDistrictName(vo.getProvName() + vo.getCityName() + vo.getDistName());
            }
        }
        user.setPosts(postService.selectPostsListByUserId(user.getUserId()));
        user.setPostIds(user.getPosts().stream().map(LogiSysPost::getPostId).collect(Collectors.toList()));
        user.setRoles(roleService.selectRolesByUserId(user.getUserId()));
        user.setRoleKeys(user.getRoles().stream().map(LogiSysRole::getRoleKey).collect(Collectors.toSet()));
        user.setRoleIds(user.getRoles().stream().map(LogiSysRole::getRoleId).collect(Collectors.toList()));
        user.setDept(extService.queryByDeptId(user.getDeptId()));
        return user;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @LogiDataScope(deptAlias = "d", userAlias = "u")
    public TableDataInfo<LogiSysUser> selectAllocatedList(LogiSysUser user) {
        return PageUtils.buildDataInfo(baseMapper.selectAllocatedList(PageUtils.buildPage(), user));
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @LogiDataScope(deptAlias = "d", userAlias = "u")
    public TableDataInfo<LogiSysUser> selectUnallocatedList(LogiSysUser user) {
        return PageUtils.buildDataInfo(baseMapper.selectUnallocatedList(PageUtils.buildPage(), user));
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public LogiSysUser selectUserByUserName(String userName) {
        return CacheUtils.getCache(userName, CacheKeyEnums.LogiUserName, LogiSysUser.class, () -> {
            return getCacheUserByName(userName);
        });
    }

    @Override
    public LogiSysUser selectUserByPhone(String phone) {
        return CacheUtils.getCache(phone, CacheKeyEnums.LogiUserPhone, LogiSysUser.class, () -> {
            return getCacheUserByPhone(phone);
        });
    }

    @Override
    public LogiSysUser selectUserByEmail(String email) {
        return CacheUtils.getCache(email, CacheKeyEnums.LogiUserEmail, LogiSysUser.class, () -> {
            return getCacheUserByEmail(email);
        });
    }

    @Override
    public LogiSysUser selectUserByUserNameAndDept(String userName, String deptName) {
        return fillDept(baseMapper.selectUserByUserNameByDept(userName, deptName));
    }

    @Override
    public LogiSysUser selectUserByPhoneAndDept(String phone, String deptName) {
        return fillDept(baseMapper.selectUserByPhoneByDept(phone, deptName));
    }

    @Override
    public LogiSysUser selectUserByEmailAndDept(String email, String deptName) {
        return fillDept(baseMapper.selectUserByEmailByDept(email, deptName));
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public LogiSysUser selectUserById(Long userId) {
        return CacheUtils.getCache(userId, CacheKeyEnums.LogiUser, LogiSysUser.class, () -> {
            return getCacheUserById(userId);
        });
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<LogiSysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (LogiSysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (Validator.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<LogiSysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (LogiSysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (Validator.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        Long count = count(new LambdaQueryWrapper<LogiSysUser>().eq(LogiSysUser::getUserName, userName).last("limit 1"));
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户手机是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(LogiSysUser user) {
        user.setMainDept("");
        if (user.getDeptId() != 0L) {
            LogiSysDept dept = deptService.getById(user.getDeptId());
            user.setMainDept(String.valueOf(dept.getMainDeptId()));
        }
        int flag = 0;
        if (StrUtil.isNotBlank(user.getMainDept())) {
            flag = 1;
        }
        LogiSysUser user1 = baseMapper.getPhone(flag, user.getPhonenumber(), user.getMainDept(), SecurityUtils.AdminRoleEnum.ADMIN.getRole());
        if (ObjectUtil.isNotEmpty(user1) && !user1.getUserId().equals(ObjectUtil.defaultIfNull(user.getUserId(), 0L))) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(LogiSysUser user) {
        Long userId = Validator.isNull(user.getUserId()) ? -1L : user.getUserId();
        LogiSysUser info = getOne(new LambdaQueryWrapper<LogiSysUser>()
                .select(LogiSysUser::getUserId, LogiSysUser::getEmail)
                .eq(LogiSysUser::getEmail, user.getEmail()).last("limit 1"));
        if (Validator.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(LogiSysUser user) {
        user.setRoleKeys(permissionService.getRolePermission(user.getUserId()));
        if (Validator.isNotNull(user.getUserId()) && SecurityUtils.isAdmin(user.getUserId())) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(LogiSysUser user) {
        // 新增用户信息
        int rows = baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);

        //缓存
        getCacheUserById(user.getUserId());

        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(LogiSysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<LogiSysUserRole>().eq(LogiSysUserRole::getUserId, userId));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.delete(new LambdaQueryWrapper<LogiSysUserPost>().eq(LogiSysUserPost::getUserId, userId));
        // 新增用户与岗位管理
        insertUserPost(user);
        //不能修改密码
        user.setPassword(null);

        return this.updateUserById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserBasic(LogiSysUser user) {
        int ret = this.updateUserById(user);
        if (ObjectUtil.isNotEmpty(user.getDept())) {
            extService.updateByEditBo(BeanUtil.toBean(user.getDept(), LogiSysDeptExtCusEditBo.class));
        }

        if (CollUtil.isNotEmpty(user.getRoleIds())) {
            // 删除用户与角色关联
            userRoleMapper.delete(new LambdaQueryWrapper<LogiSysUserRole>().eq(LogiSysUserRole::getUserId, user.getUserId()));
            // 新增用户与角色管理
            insertUserRole(user);
        }

        if (CollUtil.isNotEmpty(user.getPostIds())) {
            // 删除用户与岗位关联
            userPostMapper.delete(new LambdaQueryWrapper<LogiSysUserPost>().eq(LogiSysUserPost::getUserId, user.getUserId()));
            // 新增用户与岗位管理
            insertUserPost(user);
        }

        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateUserBasic(List<LogiSysUser> userList) {
        boolean ret = this.updateBatchById(userList);
        userList.forEach(user -> {
            if (ObjectUtil.isNotEmpty(user.getDept())) {
                extService.updateByEditBo(BeanUtil.toBean(user.getDept(), LogiSysDeptExtCusEditBo.class));
            }
            /*LogiSysUser user1 = baseMapper.selectUserById(user.getUserId());
            CacheUser(user1);*/
        });
        return ret;
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserStatus(LogiSysUser user) {
        return this.updateUserById(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserProfile(LogiSysUser user) {
        return this.updateUserById(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return updateUserByName(new LogiSysUser().setUserName(userName).setAvatar(avatar)) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resetPwd(LogiSysUser user) {
        int ret = this.updateUserById(user);
        LogiSysUser user1 = getCacheUserById(user.getUserId());
        if (ObjectUtil.isNotEmpty(user1)) {
            R<Boolean> smsSendR = smsService.resetPasswd(user1.getPhonenumber(), user.getOrignalPwd(), user1.getDept().getMainDeptId()+"", SecurityConstants.INNER);
            FeignResultUtils.throwIfFailed(smsSendR);
        }
        return ret;
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return updateUserByName(new LogiSysUser().setUserName(userName).setPassword(password));
    }

    @Override
    public int resetUserPwd(Long userId, String password) {
        return updateUserById(new LogiSysUser().setUserId(userId).setPassword(password));
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(LogiSysUser user) {
        List<Long> roles = user.getRoleIds();
        if (Validator.isNotNull(roles)) {
            // 新增用户与角色管理
            List<LogiSysUserRole> list = new ArrayList<LogiSysUserRole>();
            for (Long roleId : roles) {
                LogiSysUserRole ur = new LogiSysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<LogiSysUserRole> list = new ArrayList<LogiSysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                LogiSysUserRole ur = new LogiSysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(LogiSysUser user) {
        List<Long> posts = user.getPostIds();
        if (Validator.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<LogiSysUserPost> list = new ArrayList<LogiSysUserPost>();
            for (Long postId : posts) {
                LogiSysUserPost up = new LogiSysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<LogiSysUserRole>().eq(LogiSysUserRole::getUserId, userId));
        // 删除用户与岗位表
        userPostMapper.delete(new LambdaQueryWrapper<LogiSysUserPost>().eq(LogiSysUserPost::getUserId, userId));

        return baseMapper.deleteById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new LogiSysUser().setUserId(userId));
        }
        List<Long> ids = Arrays.asList(userIds);
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<LogiSysUserRole>().in(LogiSysUserRole::getUserId, ids));
        // 删除用户与岗位表
        userPostMapper.delete(new LambdaQueryWrapper<LogiSysUserPost>().in(LogiSysUserPost::getUserId, ids));

        remove(ids);
        return baseMapper.deleteBatchIds(ids);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<LogiSysUser> userList, Boolean isUpdateSupport, String operName) {
        if (Validator.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        /*String password = configService.selectConfigByKey("sys.user.initPassword");
        for (LogiSysUser user : userList) {
            try {
                // 验证是否存在这个用户
                LogiSysUser u = baseMapper.selectUserByUserName(user.getUserName());
                if (Validator.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }*/
        return successMsg.toString();
    }

    @Override
    public List<String> selectUserNameByPostCodeAndDeptId(String postCode, Long deptId) {
        return baseMapper.selectUserNameByPostCodeAndDeptId(postCode, deptId);
    }

    @Override
    public List<LogiSysUser> getUserByDeptId(Long deptId) {
//		LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = Wrappers.lambdaQuery();
//		userLambdaQueryWrapper.eq(SysUser::getDept,deptId);
//		List<SysUser> userList = list(userLambdaQueryWrapper);
        LogiSysUser user = new LogiSysUser();
        user.setDeptId(deptId);
        List<LogiSysUser> userList = selectUserList(user);
        return userList;
    }

    @Override
    public List<LogiSysUser> getUserByDeptIds(List<Long> deptIds) {
        List<LogiSysUser> userList = lambdaQuery().in(LogiSysUser::getDeptId, deptIds).list();
        return userList;
    }

    @Override
    public List<LogiSysUser> queryUserAll(Long mainDeptId) {
        LogiSysUser user = new LogiSysUser();
        user.setDept((LogiSysDeptExtVo) new LogiSysDeptExtVo().setMainDeptId(mainDeptId));
        return getUsersFillDept(baseMapper.selectUserList(user));
    }

    @Override
    public List<LogiSysUser> getUsersByPhoneNumber(String phoneNumber) {
        List<LogiSysUser> list = lambdaQuery().eq(LogiSysUser::getUserName, phoneNumber).or().eq(LogiSysUser::getPhonenumber, phoneNumber).list();
        return list;
    }

    private int updateUserById(LogiSysUser user) {

        int update = baseMapper.updateById(user);

        /*LogiSysUser user1 = baseMapper.selectUserById(user.getUserId());
        if (ObjectUtil.isNotEmpty(user1)) {
            CacheUser(user1);
        }*/

        return update;
    }

    private int updateUserByName(LogiSysUser user) {

        LogiSysUser user1 = baseMapper.selectOne(new LambdaQueryWrapper<LogiSysUser>().eq(LogiSysUser::getUserName, user.getUserName()));

        user.setUserId(user1.getUserId());

        return updateUserById(user);
    }

    private LogiSysUser getCacheUserById(Long userId) {

        LogiSysUser user1 = baseMapper.selectUserById(userId);

        if (ObjectUtil.isNotEmpty(user1)) {
            fillDept(user1);
//            CacheUser(user1);
        }

        return user1;

    }

    private LogiSysUser getCacheUserByName(String userName) {

        LogiSysUser user1 = baseMapper.selectUserByUserName(userName);

        if (ObjectUtil.isNotEmpty(user1)) {
            fillDept(user1);
//            CacheUser(user1);
        }

        return user1;
    }

    private LogiSysUser getCacheUserByPhone(String phone) {

        LogiSysUser user1 = baseMapper.selectUserByPhone(phone);

        if (ObjectUtil.isNotEmpty(user1)) {
            fillDept(user1);
//            CacheUser(user1);
        }

        return user1;
    }

    private LogiSysUser getCacheUserByEmail(String email) {

        LogiSysUser user1 = baseMapper.selectUserByEmail(email);

        if (ObjectUtil.isNotEmpty(user1)) {
            fillDept(user1);
//            CacheUser(user1);
        }

        return user1;
    }

    private LogiSysUser selectUserByPhoneAndMainDeptId(String phone, Long mainDeptId) {

        LogiSysUser user1 = baseMapper.selectUserByPhoneAndMainDeptId(phone,mainDeptId.toString());

        if (ObjectUtil.isNotEmpty(user1)) {
            fillDept(user1);
//            CacheUser(user1);
        }

        return user1;
    }

    @Override
    public void CacheUser(LogiSysUser user) {
        //缓存
        CacheUtils.cache(user, CacheKeyEnums.LogiUser.getKey(user.getUserId()), CacheKeyEnums.LogiUser.getTime(), TimeUnit.DAYS);
        CacheUtils.cache(user, CacheKeyEnums.LogiUserName.getKey(user.getUserName()), CacheKeyEnums.LogiUser.getTime(), TimeUnit.DAYS);
        CacheUtils.cache(user, CacheKeyEnums.LogiUserPhone.getKey(user.getPhonenumber()), CacheKeyEnums.LogiUser.getTime(), TimeUnit.DAYS);
        CacheUtils.cache(user, CacheKeyEnums.LogiUserEmail.getKey(user.getEmail()), CacheKeyEnums.LogiUser.getTime(), TimeUnit.DAYS);
    }

    @Override
    public void remove(Long userId) {
        CacheUtils.remove(userId, CacheKeyEnums.LogiUser);
        LogiSysUser user = this.getById(userId);
        CacheUtils.remove(user.getPhonenumber(), CacheKeyEnums.LogiUserPhone);
        CacheUtils.remove(user.getUserName(), CacheKeyEnums.LogiUserName);
        CacheUtils.remove(user.getEmail(), CacheKeyEnums.LogiUserEmail);
        this.deleteUserById(userId);
    }

    @Override
    public void remove(List<Long> userIds) {
        List<LogiSysUser> users = baseMapper.selectBatchIds(userIds);
        if (CollUtil.isEmpty(users)) {
            return;
        }
        users.forEach(user -> {
            CacheUtils.remove(user.getUserId(), CacheKeyEnums.LogiUser);
            CacheUtils.remove(user.getUserName(), CacheKeyEnums.LogiUserName);
            CacheUtils.remove(user.getEmail(), CacheKeyEnums.LogiUserEmail);
            CacheUtils.remove(user.getPhonenumber(), CacheKeyEnums.LogiUserPhone);
            this.deleteUserById(user.getUserId());
        });
    }

    @Override
    public void checkUserDataScope(Long userId) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            LogiSysUser user = new LogiSysUser();
            user.setUserId(userId);
            List<LogiSysUser> users = this.selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new BaseException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        baseMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogiSysUser register(LogiSysUser user) {

        user.setCreateBy(user.getPhonenumber());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCheckStatus("0");
        user.setStatus("1");
        /*List<Long> ids = new ArrayList<>();
        ids.add(roleService.selectRoleByKey("admin").getRoleId());
        //user.setRoleIds(ids);*/
        LogiSysDept dept = new LogiSysDept().setParentId(0L).setStatus("1").setCreateBy("admin").setCreateTime(new Date());
        deptService.insertDept(dept);
        dept.setMainDeptId(dept.getDeptId());
        deptService.updateById(dept);
        user.setDeptId(dept.getDeptId());
        user.setRoleIds(Lists.newArrayList(SecurityUtils.AdminRoleEnum.ADMIN.getUserId()));
        List<Long> postIds = postService.selectPostList(new LogiSysPost().setPostCode(SecurityUtils.PostEnum.DIRECTOR.getCode())).stream().map(LogiSysPost::getPostId).collect(Collectors.toList());
        user.setPostIds(postIds);
        insertUser(user);
        return user;

    }

    @Override
    public List<LogiSysUser> selectUserByPhones(List<String> phoneNumbers) {
        if (CollUtil.isEmpty(phoneNumbers)) {
            return Lists.newArrayList();
        }
        return baseMapper.selectUserByPhones(phoneNumbers);
    }

    @Override
    public List<LogiSysUser> selectUserByIds(List<Long> idList) {
        return baseMapper.selectUserByIds(idList);
    }

    @Override
    public LogiSysUser selectMainUserByPhone(String phone) {
        return baseMapper.selectUserByPhoneAndRole(phone, SecurityUtils.AdminRoleEnum.ADMIN.getRole());
    }

    @Override
    public List<LogiSysUser> getNotify(Long userId, String postCode) {
        // 获取本用户的部门&上级部门&服务商部门
        LogiSysUser user = this.getCacheUserById(userId);
        List<Long> deptIds = Lists.newArrayList(user.getDept().getDeptId(), user.getDept().getParentId(), user.getDept().getMainDeptId());
        deptIds = deptIds.stream().distinct().collect(Collectors.toList());
        return baseMapper.getNotifyUser(userId, postCode, deptIds);
    }

    @Override
    public List<LogiSysUser> getNotify(String phone, Long deptId, String postCode) {
        // 获取本用户的部门&上级部门&服务商部门
        LogiSysDeptExtVo deptVo = deptService.selectDeptById(deptId);
        LogiSysUser user = this.selectUserByPhoneAndMainDeptId(phone, deptVo.getMainDeptId());
        List<Long> deptIds = Lists.newArrayList(user.getDept().getDeptId(), user.getDept().getParentId(), user.getDept().getMainDeptId());
        deptIds = deptIds.stream().distinct().collect(Collectors.toList());
        return baseMapper.getNotifyUser(user.getUserId(), postCode, deptIds);
    }

    @Override
    public LogiSysUser changeUserPhone(String oldPhone, String oldPhoneCode, String newPhone, String newPhoneCode) {
        if (!CacheUtils.hasKey(CacheKeyEnums.RegUserSms.getKey(oldPhone))) {
            throw new BaseException("旧手机号验证码已过期!");
        }
        if (!CacheUtils.hasKey(CacheKeyEnums.RegUserSms.getKey(newPhone))) {
            throw new BaseException("新手机号验证码已过期!");
        }
        if (!StrUtil.equals(oldPhoneCode, CacheUtils.getCache(CacheKeyEnums.RegUserSms.getKey(oldPhone), String.class))) {
            throw new BaseException("旧手机号验证码不正确!");
        }
        if (!StrUtil.equals(newPhoneCode, CacheUtils.getCache(CacheKeyEnums.RegUserSms.getKey(newPhone), String.class))) {
            throw new BaseException("新手机号验证码不正确!");
        }
        Long userId = SecurityUtils.getUserId();
        LogiSysUser user = getCacheUserById(userId);
        if (!newPhone.equals(user.getPhonenumber())) {
            user.setPhonenumber(newPhone);
            if (StringUtils.isNotEmpty(user.getPhonenumber())
                    && UserConstants.NOT_UNIQUE.equals(checkPhoneUnique(user))) {
                throw new GlobalException("更换用户手机号失败【" + user.getPhonenumber() + "】失败，手机号码已存在");
            }

            if (user.getRoleKeys().contains(SecurityUtils.AdminRoleEnum.ADMIN.getRole())) {
                LogiSysUser logiSysUser = selectMainUserByPhone(newPhone);
                if (ObjectUtil.isNotEmpty(logiSysUser)) {
                    throw new GlobalException("更换用户手机号失败，用户已经注册服务商【" + logiSysUser.getDept().getMainDeptId() + "】");
                }
            }

            LogiSysUser update = (LogiSysUser) new LogiSysUser().setUserId(user.getUserId()).setPhonenumber(newPhone).setUpdateBy(SecurityUtils.getPhone()).setUpdateTime(new Date());
            this.updateUserById(update);
        }
        // 添加变更手机号记录
        DateTime now = DateUtil.date();
        LogiAccountLog accountLog = new LogiAccountLog();
        accountLog.setUserId(user.getUserId());
        accountLog.setMatter("更改手机号");
        accountLog.setDeptId(user.getDeptId());
        accountLog.setPhonenumber(user.getPhonenumber());
        accountLog.setOperTime(now);
        accountLog.setCreateBy(user.getUserName());
        accountLog.setCreateTime(now);
        accountLog.setUpdateBy(user.getUserName());
        accountLog.setUpdateTime(now);
        logiAccountLogService.save(accountLog);
        return getCacheUserById(userId);
    }

}
